package com.hnas.mrch.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnas.api.domain.ResultCode;
import com.hnas.api.domain.RouteFinalValue;
import com.hnas.api.dto.DTOApiResponse;
import com.hnas.api.dto.DTOResult;
import com.hnas.api.interfacebeans.CreateShopQRCodeFromServer;
import com.hnas.api.interfacebeans.CreateShopQRCodeReceiveServer;
import com.hnas.api.server.PostConnServer;
import com.hnas.api.util.AESTool;
import com.hnas.api.util.CommonUtil;
import com.hnas.common.web.BaseAjaxResponse;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.dto.DataBean;
import com.hnas.core.util.StringUtil;
import com.hnas.hnt.orm.EQPInfo;
import com.hnas.hnt.orm.Industry;
import com.hnas.hnt.orm.Mrch;
import com.hnas.hnt.orm.SubJectDic;
import com.hnas.hnt.service.IIndustryService;
import com.hnas.hnt.service.IMrchService;
import com.hnas.hnt.service.SubJectDicService;
import com.hnas.mrch.service.GenerateMrchTwoCodeService;
import com.hnas.mrch.service.dto.DTOGenerateMrchTwoCode;
import com.hnas.mrch.service.dto.search.DTOGenerateMrchTwoCodeSearch;

@Controller
@RequestMapping("/backend/generateMrchTwoCode")
public class GenerateMrchTwoCodeControl {

	private static Log log = LogFactory.getLog(GenerateMrchTwoCodeControl.class);

	private static ObjectMapper objectMapper = new ObjectMapper();

	private AESTool aes = new AESTool();

	@Autowired
	private GenerateMrchTwoCodeService generateMrchTwoCodeService;

	@Autowired
	private IMrchService MrchService;

	@Autowired
	private IIndustryService industryService;

	@Autowired
	private PostConnServer postConnServer;

	@Autowired
	private SubJectDicService subJectDicService;

	public List<Mrch> mrchs = new ArrayList<Mrch>();

	public List<SubJectDic> subDics = new ArrayList<SubJectDic>();

	@RequestMapping("/search")
	public String search(ModelMap modelMap, HttpServletRequest request, @ModelAttribute("criteria") DTOGenerateMrchTwoCodeSearch criteria) {
		try {
			criteria.setTotalCount(-1);
			DTOPagedList<DTOGenerateMrchTwoCode> pg = this.generateMrchTwoCodeService.search(criteria);
			String industryIds = "";
			List<Industry> list = industryService.getAllIndustry();
			if (null != list && list.size() > 0) {
				for (Industry i : list) {
					if (StringUtil.isEmpty(industryIds)) {
						industryIds = i.getINDUSTRY_ID();
					} else {
						industryIds += "," + i.getINDUSTRY_ID();
					}
				}
			}
			mrchs = this.MrchService.getMrchsByIndustryId(industryIds);
			subDics = this.subJectDicService.getSubJectDics();
			modelMap.put("pg", pg);
			modelMap.put("dto", criteria);
		} catch (Exception e) {
			log.error("", e);
			modelMap.put("resultSize", 0);
		}
		modelMap.put("pageTitle", "商家生成二维码");

		List<DataBean> beans = new ArrayList<DataBean>();
		beans.add(new DataBean("mrchName", "mrchName", "商户名称", false, 255));
		beans.add(new DataBean("mrchId", "mrchId", "商户编号", true, 255));
		beans.add(new DataBean("termNo", "termNo", "终端编号", false, 255));
		beans.add(new DataBean("eqpName", "eqpName", "终端名称", false, 255));
		beans.add(new DataBean("subName", "subName", "支持科目名称", false, 355));
		beans.add(new DataBean("discount", "discount", "折扣率(%)", false, 255));
		beans.add(new DataBean("picName", "picName", "图片名称", false, 255));
		beans.add(new DataBean("qrcodeNo", "qrcodeNo", "二维码标识", false, 255));
		beans.add(new DataBean("qrcodePath", "qrcodePath", "二维码路径", false, 255));
		beans.get(beans.size() - 1).setDisplay(false);
		beans.add(new DataBean("remark", "remark", "备注", true, 255));
		beans.get(beans.size() - 1).setDisplay(false);

		modelMap.put("beans", beans);
		return "backend/mrch/list_generate_mrch_qrcode";
	}

	@RequestMapping(value = "show/{id}", method = RequestMethod.POST)
	@ResponseBody
	public DTOGenerateMrchTwoCode show(@PathVariable("id") Long id) {
		DTOGenerateMrchTwoCode dto = this.generateMrchTwoCodeService.getGenerateMrchTwoCode(id);
		return dto;
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse add(DTOGenerateMrchTwoCode dto) {
		return this.save(dto);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse save(DTOGenerateMrchTwoCode dto) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		DTOGenerateMrchTwoCode vo = this.generateMrchTwoCodeService.getMrchTwoCodeByMrchIdAndTermNo(dto.getMrchId(), dto.getTermNo());
		if (vo != null && vo.getId() != dto.getId()) {
			res.setResult(2);
			res.setErrorMessage("商户编号与终端编号组合重复");
			return res;
		}

		try {
			List<CreateShopQRCodeFromServer> fromServerList = null;
			List<CreateShopQRCodeReceiveServer> receiveServerList = new ArrayList<CreateShopQRCodeReceiveServer>();
			CreateShopQRCodeReceiveServer receiveServer = new CreateShopQRCodeReceiveServer();
			receiveServer.setMerchantId(dto.getMrchId());
			receiveServer.setShopName(dto.getMrchName());
			receiveServer.setTermNo(dto.getTermNo());
			receiveServer.setSubCode(dto.getSubCode());
			receiveServer.setData1(dto.getEqpName()); // 档口名称
			receiveServer.setData2(dto.getDiscount()); // 折扣
			receiveServerList.add(receiveServer);
			DTOApiResponse dtoResponse = postConnServer.getRequestData(receiveServerList, RouteFinalValue.APP_CreateHasTremNoShopQRCode, false);
			if (null != dtoResponse) {
				DTOResult dtoResult = dtoResponse.getResult();
				String resultcode = dtoResult.getResultCode();
				if (ResultCode.SUCCESS.equals(resultcode)) {
					String resultData = dtoResult.getResultData();
					fromServerList = new ArrayList<CreateShopQRCodeFromServer>();
					if (StringUtil.isNotEmpty(resultData)) {
						// resultData = aes.decrypt(resultData,
						// dtoResponse.getKey());// 解密
						if (StringUtil.isNotEmpty(resultData)) {
							JavaType javaType = CommonUtil.getCollectionType(ArrayList.class, CreateShopQRCodeFromServer.class);
							fromServerList = (List<CreateShopQRCodeFromServer>) objectMapper.readValue(resultData, javaType);
						}
					}
				}
			}
			if (null != fromServerList && fromServerList.size() > 0) {
				CreateShopQRCodeFromServer qrCode = fromServerList.get(0);
				if (StringUtil.isNotEmpty(qrCode.getQrcodeNo()) && dto.getMrchId().equals(qrCode.getMerchantId()) && dto.getTermNo().equals(qrCode.getTremNo())) {
					dto.setQrcodeNo(qrCode.getQrcodeNo());
					String picName = dto.getMrchName() + "_" + dto.getTermNo() + ".jpg";
					dto.setPicName(picName);
				} else {
					res.setResult(2);
					res.setErrorMessage("生成商户二维码失败，返回信息不正确！");
					return res;
				}
			} else {
				res.setResult(2);
				res.setErrorMessage("服务异常，生成商户二维码失败，请稍后再试！");
				return res;
			}

			this.generateMrchTwoCodeService.saveGenerateMrchTwoCode(dto);
			res.setResult(1);
		} catch (Exception e) {
			res.setErrorMessage(e.getMessage());
		}
		return res;
	}

	@RequestMapping(value = "disable/{id}", method = RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse disable(@PathVariable("id") Long id) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			this.generateMrchTwoCodeService.disableGenerateMrchTwoCode(id);
			res.setResult(1);
		} catch (Exception e) {
			res.setResult(2);
		}

		return res;
	}

	/**
	 * 查商家
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "getMrchs")
	@ResponseBody
	public List<Mrch> getMrchs(HttpServletRequest request, HttpServletResponse response) {
		String industryIds = "";
		List<Industry> list = industryService.getAllIndustry();
		if (null != list && list.size() > 0) {
			for (Industry i : list) {
				if (StringUtil.isEmpty(industryIds)) {
					industryIds = i.getINDUSTRY_ID();
				} else {
					industryIds += "," + i.getINDUSTRY_ID();
				}
			}
		}
		List<Mrch> mrchsByIndustryId = this.MrchService.getMrchsByIndustryId(industryIds);
		return mrchsByIndustryId;
	}

	/**
	 * 终端号
	 * 
	 * @param request
	 * @param response
	 * @param mrchId
	 */
	@RequestMapping(value = "getTerminalNo")
	@ResponseBody
	public List<EQPInfo> getTerminalNo(HttpServletRequest request, HttpServletResponse response, String mrchId) {
		List<EQPInfo> list = new ArrayList<EQPInfo>();
		try {
			if(StringUtil.isNotEmpty(mrchId)){
				list = this.MrchService.getEQPsByMrchId(mrchId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 获取科目
	 * 
	 * @param request
	 * @param response
	 * @param mrchId
	 */
	@RequestMapping(value = "getSubJectDics")
	@ResponseBody
	public List<SubJectDic> getSubJectDics(HttpServletRequest request, HttpServletResponse response) {
		return subDics;
	}

}
